# backend/api/v1/auth.py
from fastapi import APIRouter, Depends, HTTPException, status, Body
from sqlalchemy.ext.asyncio import AsyncSession
from datetime import datetime, timedelta
from jose import jwt, JWTError

from backend.core.security import create_access_token
from backend.core.config import settings
from backend.schemas.token import Token
from backend.database import get_db
from backend.crud.user import authenticate_user

router = APIRouter()

# 登录接口 - 不需要认证
@router.post("/login", response_model=Token)
async def login(
    email: str = Body(...),
    password: str = Body(...),
    captcha_token: str = Body(...),
    user_offset: int = Body(...),
    db: AsyncSession = Depends(get_db)
):
    """
    用户登录（包含滑块验证码验证）
    """
    # 1. 验证滑块验证码是否已验证
    from backend.utils.cache import redis_client

    # 检查已验证状态
    if redis_client:
        verified_key = f"captcha:verified:{captcha_token}"
        correct_offset = redis_client.get(verified_key)

        if not correct_offset:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="验证码未验证或已过期"
            )

        # 删除已验证标记
        redis_client.delete(verified_key)
        correct_offset = int(correct_offset)
    else:
        # 如果没有Redis，回退到原始逻辑
        from backend.utils.cache import get_captcha
        correct_offset = get_captcha(captcha_token)
        if not correct_offset:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="验证码已过期或不存在"
            )

    # 2. 验证用户凭证
    user = await authenticate_user(db, email=email, password=password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )

    # 3. 生成JWT token
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.email}, expires_delta=access_token_expires
    )

    return {"access_token": access_token, "token_type": "bearer"}